<template>
  <el-form
    class="login-form"
    status-icon
    :rules="loginRules"
    ref="loginForm"
    :model="loginForm"
    label-width="0"
  >
    <el-form-item prop="username">
      <el-input
        size="small"
        v-model="loginForm.username"
        auto-complete="off"
        placeholder="请输入账号"
      >
        <i slot="prefix" class="el-icon-user"></i>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        size="small"
        :type="passwordType"
        v-model="loginForm.password"
        auto-complete="off"
        placeholder="请输入密码"
        @keyup.enter.native="handleLogin"
      >
        <i
          class="el-icon-view el-input__icon"
          slot="suffix"
          @click="showPassword"
        ></i>
        <i slot="prefix" class="el-icon-unlock"></i>
      </el-input>
    </el-form-item>
    <el-form-item prop="code">
      <el-input
        size="small"
        v-model="code"
        auto-complete="off"
        placeholder="验证码"
        style="width: 63%"
        @keyup.enter.native="handleLogin"
      >
        <!-- <svg-icon slot="prefix" icon-class="validCode" /> -->
        <i slot="prefix" class="el-icon-key"></i>
      </el-input>
      <div class="login-code">
        <img :src="codeUrl" @click="getCode" class="login-code-img" />
      </div>
    </el-form-item>
    <el-checkbox v-model="rememberMe" style="margin: 0px 0px 10px 10px"
      >记住密码</el-checkbox
    >
    <el-form-item>
      <el-button
        type="primary"
        size="small"
        @keyup.enter="keyDown"
        @click="checkCode"
        class="login-submit"
        >登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { getCaptcha, checkCaptcha } from "@/api/user";
export default {
  name: "userlogin",
  data() {
    return {
      //验证码图片
      codeUrl: "",
      //请求基地址
      baseURL: process.env.BASE_API,
      //登录表单
      loginForm: {
        //用户名
        username: "",
        //密码
        password: "",
      },
      //记住密码
      rememberMe: true,
      //验证码
      code: "",
      //保存上一次请求的sessionid
      sessionId: "",
      //登录表单验证规则
      loginRules: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "密码长度最少为6位", trigger: "blur" },
        ],
      },
      passwordType: "password",
    };
  },
  created() {
    this.getCookie();
    this.getCode();
  },
  mounted() {
    //绑定回车登录事件
    window.addEventListener("keydown", this.keyDown);
  },
  destroyed() {
    //销毁事件
    window.removeEventListener("keydown", this.keyDown, false);
  },
  computed: {},
  props: [],
  methods: {
    //显示密码
    showPassword() {
      this.passwordType === ""
        ? (this.passwordType = "password")
        : (this.passwordType = "");
    },
    //获取cookie
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    //获取验证码
    getCode() {
      getCaptcha().then((res) => {
        if (res.success) {
          this.codeUrl = res.data.img;
          this.sessionId = res.data.id;
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    //检查验证码
    checkCode() {
      if (this.code === "") {
        this.$message.warning("请输入验证码");
        return;
      }
      checkCaptcha(this.code, this.sessionId).then((res) => {
        if (res.success) {
          this.handleLogin();
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    //登录
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          if (this.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          const loading = this.$loading({
            lock: true,
            text: "登录中,请稍后。。。",
            spinner: "el-icon-loading",
          });
          this.$store
            .dispatch("user/Login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" });
              loading.close();
            })
            .catch(() => {
              loading.close();
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //回车登录
    keyDown(e) {
      //如果是回车则执行登录方法
      if (e.keyCode == 13) {
        //需要执行的登录方法
        this.handleLogin();
      }
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.login-code-img {
  height: 38px;
}
</style>
